package com.datagateway.controller;

import com.datagateway.component.MemoryManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 内存管理控制器
 * 提供内存监控和优化的API接口
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/memory")
public class MemoryManagementController {

    @Autowired
    private MemoryManager memoryManager;

    /**
     * 获取内存使用情况
     * 
     * @return 内存使用情况
     */
    @GetMapping("/usage")
    public Map<String, Object> getMemoryUsage() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            MemoryManager.MemoryUsageInfo usage = memoryManager.getMemoryUsage();
            
            result.put("success", true);
            result.put("usage", usage);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取内存使用情况失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取内存统计信息
     * 
     * @return 内存统计信息
     */
    @GetMapping("/statistics")
    public Map<String, Object> getMemoryStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            MemoryManager.MemoryStatistics statistics = memoryManager.getStatistics();
            
            result.put("success", true);
            result.put("statistics", statistics);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取内存统计信息失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取内存池信息
     * 
     * @return 内存池信息
     */
    @GetMapping("/pools")
    public Map<String, Object> getMemoryPools() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, MemoryManager.MemoryPoolInfo> pools = memoryManager.getMemoryPools();
            
            result.put("success", true);
            result.put("pools", pools);
            result.put("poolCount", pools.size());
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取内存池信息失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 手动触发内存清理
     * 
     * @return 操作结果
     */
    @PostMapping("/cleanup")
    public Map<String, Object> triggerMemoryCleanup() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            memoryManager.triggerMemoryCleanup();
            
            result.put("success", true);
            result.put("message", "内存清理已触发");
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "触发内存清理失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 设置自动清理配置
     * 
     * @param request 自动清理配置请求
     * @return 操作结果
     */
    @PostMapping("/auto-cleanup/config")
    public Map<String, Object> setAutoCleanupConfig(@RequestBody AutoCleanupConfigRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            memoryManager.setAutoCleanupConfig(
                request.isEnabled(),
                request.getInterval(),
                request.getThreshold()
            );
            
            result.put("success", true);
            result.put("enabled", request.isEnabled());
            result.put("interval", request.getInterval());
            result.put("threshold", request.getThreshold());
            result.put("message", "自动清理配置已更新");
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置自动清理配置失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取内存优化建议
     * 
     * @return 优化建议
     */
    @GetMapping("/optimization-suggestions")
    public Map<String, Object> getOptimizationSuggestions() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            MemoryManager.MemoryStatistics statistics = memoryManager.getStatistics();
            MemoryManager.MemoryUsageInfo usage = memoryManager.getMemoryUsage();
            
            result.put("success", true);
            result.put("suggestions", statistics.getLastOptimizationSuggestion());
            result.put("heapUsagePercent", usage.getHeapUsagePercent());
            result.put("nonHeapUsagePercent", usage.getNonHeapUsagePercent());
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取优化建议失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取内存使用趋势
     * 
     * @return 内存使用趋势
     */
    @GetMapping("/trend")
    public Map<String, Object> getMemoryTrend() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            MemoryManager.MemoryUsageInfo usage = memoryManager.getMemoryUsage();
            MemoryManager.MemoryStatistics statistics = memoryManager.getStatistics();
            
            // 计算内存使用趋势
            Map<String, Object> trend = new HashMap<>();
            trend.put("heapUsagePercent", usage.getHeapUsagePercent());
            trend.put("nonHeapUsagePercent", usage.getNonHeapUsagePercent());
            trend.put("totalGcCount", statistics.getTotalGcCount());
            trend.put("totalGcTime", statistics.getTotalGcTime());
            trend.put("memoryPoolCount", statistics.getMemoryPoolCount());
            
            result.put("success", true);
            result.put("trend", trend);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取内存使用趋势失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取内存健康状态
     * 
     * @return 内存健康状态
     */
    @GetMapping("/health")
    public Map<String, Object> getMemoryHealth() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            MemoryManager.MemoryUsageInfo usage = memoryManager.getMemoryUsage();
            MemoryManager.MemoryStatistics statistics = memoryManager.getStatistics();
            
            // 评估内存健康状态
            String healthStatus = "HEALTHY";
            String healthMessage = "内存使用正常";
            
            if (usage.getHeapUsagePercent() > 85) {
                healthStatus = "CRITICAL";
                healthMessage = "堆内存使用率过高";
            } else if (usage.getHeapUsagePercent() > 75) {
                healthStatus = "WARNING";
                healthMessage = "堆内存使用率较高";
            }
            
            if (usage.getNonHeapUsagePercent() > 90) {
                healthStatus = "CRITICAL";
                healthMessage = "非堆内存使用率过高";
            } else if (usage.getNonHeapUsagePercent() > 80) {
                healthStatus = "WARNING";
                healthMessage = "非堆内存使用率较高";
            }
            
            Map<String, Object> health = new HashMap<>();
            health.put("status", healthStatus);
            health.put("message", healthMessage);
            health.put("heapUsagePercent", usage.getHeapUsagePercent());
            health.put("nonHeapUsagePercent", usage.getNonHeapUsagePercent());
            health.put("totalGcCount", statistics.getTotalGcCount());
            health.put("totalGcTime", statistics.getTotalGcTime());
            
            result.put("success", true);
            result.put("health", health);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取内存健康状态失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取内存配置信息
     * 
     * @return 内存配置信息
     */
    @GetMapping("/config")
    public Map<String, Object> getMemoryConfig() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("autoCleanupEnabled", true); // 从MemoryManager获取
            config.put("cleanupInterval", 300000); // 5分钟
            config.put("cleanupThreshold", 80.0); // 80%
            config.put("heapUsageWarnThreshold", 75.0);
            config.put("heapUsageCriticalThreshold", 85.0);
            config.put("nonHeapUsageWarnThreshold", 80.0);
            config.put("nonHeapUsageCriticalThreshold", 90.0);
            
            result.put("success", true);
            result.put("config", config);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取内存配置信息失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 自动清理配置请求类
     */
    public static class AutoCleanupConfigRequest {
        private boolean enabled = true;
        private long interval = 300000; // 5分钟
        private double threshold = 80.0; // 80%

        // Getter和Setter方法
        public boolean isEnabled() { return enabled; }
        public void setEnabled(boolean enabled) { this.enabled = enabled; }
        
        public long getInterval() { return interval; }
        public void setInterval(long interval) { this.interval = interval; }
        
        public double getThreshold() { return threshold; }
        public void setThreshold(double threshold) { this.threshold = threshold; }
    }
}
